<?php
require_once PATH_FFWD.'/prototypes/module.base.php';

class BaseEditModule extends BaseModule{
	public function __construct($p){
		if(!$this->tablename)throw new Exception('Nothing else, but the TABLENAME property must be defined!!!');
		try{
			$clsn=$this->tablename.'Table';
			$this->table=new $clsn();
		}catch(Exception $e){
			global $db; 
			$db->buildTable($this->tablename);
			throw new Exception('Table has been built!');
		}
	} 
	
	public function listAction($p){
		if($this->requireAuth())return;
		global $user,$db;
		$fields=$this->table->getFields();
		$cond=Array();
		if(isset($fields['deleted_at']))$cond['deleted_at']='NULL';		
		$q=$this->table->buildQuery(array_keys($fields),$cond);		
		$rs=$db->query($q);
				
		$view=new ClistExView($this);
		$p[ACTION]='edit';
		$view->render($rs,$p);				
		
		echo html_input_button(Array(
			'value'=>translate('New'),
			'onclick'=>js_redirect(link_for(Array(ACTION=>'edit',P0=>'new')),1),
		));
	}
	
	protected function &getEditForm(){
		$clsn=$this->tablename.'Form';
		try{		
			$form=new $clsn();
		}catch(Exception $e){
			Baseform::generate($this->tablename);
			$form=new $clsn();
		}
		return $form;	
	}
		
	public function editAction($p){
		if($this->requireAuth())return;
		$form=$this->getEditForm();
		$e=$this->table->getById($p[P0]);
		$form->loadfromrecord($e);
		$form->render(Array());
	}
	
	public function deleteAction($p){
		global $app;
		if(!isset($p[P0])){
			throw new Exception('Not enough parameter: P0 not set');
		}
		$e=$this->table->getById($p[P0]);
		$e->delete();
		$app->controller->redirectTo(link_for(Array(ACTION=>'list',P0=>NULL)));		
	}
	
	public function doeditAction($p){
		if($this->requireAuth())return;
		global $app,$user;
		$form=$this->getEditForm();
		$form->process($_POST);
		$e=$this->table->getById($p[P0]);
		if($form->save($e)){
			$form->redirectWithErrorMessages('url_error');
		}else{
			$url=link_for((string)$e->id.'/edit');
			$app->redirectTo($url);
		}	
	}	
};
